package com.sky.service.impl;

import com.sky.dto.GoodsSalesDTO;
import com.sky.entity.Orders;
import com.sky.mapper.OrdersMapper;
import com.sky.mapper.UserMapper;
import com.sky.service.ReportService;
import com.sky.service.WorkspaceService;
import com.sky.vo.*;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class ReportServiceImpl implements ReportService {

    @Autowired
    private OrdersMapper ordersMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private WorkspaceService workspaceService;

    /**
     * 营业额统计接口
     * @param begin
     * @param end
     * @return
     */
    @Override
    public TurnoverReportVO turnoverStatistics(LocalDate begin, LocalDate end) {

        List<LocalDate> date = new ArrayList<>();
        //1. 循环获取日期集合
        while (!begin.isAfter(end)){
            date.add(begin);
            begin = begin.plusDays(1);
        }
        //2. 获取每日的营业额
        List<Double> moneyList = new ArrayList<>();
        //2.1 营业额的订单状态设置为已完成 5
        Integer status = Orders.COMPLETED;
        for (LocalDate localDate : date) {
            LocalDateTime minTime = LocalDateTime.of(localDate, LocalTime.MIN);
            LocalDateTime maxTime = LocalDateTime.of(localDate, LocalTime.MAX);
            //查询每天完成的营业额收入  select sum(amount) from orders where status = 5 and order_time >= '2023-08-01 00:00:00' and order_time <= '2023-08-01 23:59:59'
            Double money = ordersMapper.getSumMoney(status,minTime,maxTime);
            moneyList.add(money == null ? 0 : money);
        }
        //3. 将集合转为String
        //3.1 将日期date集合转为String
        String dateList = StringUtils.join(date,",");
        //3.2 将营业额moneyList集合转为String
        String turnoverList = StringUtils.join(moneyList,",");

        return TurnoverReportVO.builder()
                .dateList(dateList)
                .turnoverList(turnoverList)
                .build();
    }

    /**
     * 用户统计接口
     * @param begin
     * @param end
     * @return
     */
    @Override
    public UserReportVO userStatistics(LocalDate begin, LocalDate end) {
        //1. 获取日期集合
        List<LocalDate> date = new ArrayList<>();
        //1.1 循环获取日期
        while (!begin.isAfter(end)){
            date.add(begin);
            begin = begin.plusDays(1);
        }
        //2. 遍历date集合
        List<Integer> newUserSum = new ArrayList<>();
        List<Integer> allUserSum = new ArrayList<>();
        for (LocalDate localDate : date) {
            //2.1 补全时间参数
            LocalDateTime minTime = LocalDateTime.of(localDate, LocalTime.MIN);
            LocalDateTime maxTime = LocalDateTime.of(localDate, LocalTime.MAX);

            Map<String,LocalDateTime> map = new HashMap<>();
            
            //2.2 获取总用户量  select count(*) from user where create_time < '2023-08-05 23:59:59'
            map.put("maxTime",maxTime);
            Integer countAll = userMapper.getUserCount(map);
            allUserSum.add(countAll);
            //2.3 获取新增用户量
            map.put("minTime",minTime);
            Integer countNew = userMapper.getUserCount(map);
            newUserSum.add(countNew);
        }
        //3. 转为String
        String dateList = StringUtils.join(date, ",");
        String newUserList = StringUtils.join(newUserSum, ",");
        String totalUserList = StringUtils.join(allUserSum, ",");


        return UserReportVO.builder()
                .dateList(dateList)
                .newUserList(newUserList)
                .totalUserList(totalUserList)
                .build();
    }

    /**
     * 订单统计接口
     * @param begin
     * @param end
     * @return
     */
    @Override
    public OrderReportVO ordersStatistics(LocalDate begin, LocalDate end) {
        //1. 获取日期集合
        List<LocalDate> date = new ArrayList<>();
        //1.1 循环获取日期
        while (!begin.isAfter(end)){
            date.add(begin);
            begin = begin.plusDays(1);
        }

        List<Integer> total = new ArrayList<>();
        List<Integer> valid = new ArrayList<>();
        Integer totalOrderCount = 0;
        Integer validOrderCount = 0;

        for (LocalDate localDate : date) {
            LocalDateTime minTime = LocalDateTime.of(localDate, LocalTime.MIN);
            LocalDateTime maxTime = LocalDateTime.of(localDate, LocalTime.MAX);
            //2. 获取订单数列表  select count(*) from orders where order_time >= '2023-08-01 00:00:00' and order_time <= '2023-08-05 23:59:59' and status = 5
            Map<String,Object> map = new HashMap<>();
            map.put("minTime",minTime);
            map.put("maxTime",maxTime);
            Integer allOrders = ordersMapper.getCount(map);

            total.add(allOrders);
            totalOrderCount += allOrders;

            //2.1 获取有效订单列表
            map.put("status",Orders.COMPLETED);
            Integer validOrders = ordersMapper.getCount(map);

            valid.add(validOrders);
            validOrderCount += validOrders;
        }
        //3. 获取订单完成率
        Double orderCompletionRate = validOrderCount*1.0 / totalOrderCount;
        return OrderReportVO.builder()
                .dateList(StringUtils.join(date,","))
                .orderCompletionRate(orderCompletionRate)
                .orderCountList(StringUtils.join(total,","))
                .totalOrderCount(totalOrderCount)
                .validOrderCount(validOrderCount)
                .validOrderCountList(StringUtils.join(valid,","))
                .build();
    }

    /**
     * 查询销量排名top10接口
     * @param begin
     * @param end
     * @return
     */
    @Override
    public SalesTop10ReportVO top10(LocalDate begin, LocalDate end) {
        //1. 补全时间信息
        LocalDateTime minTime = LocalDateTime.of(begin, LocalTime.MIN);
        LocalDateTime maxTime = LocalDateTime.of(end, LocalTime.MAX);

        Map<String,Object> map = new HashMap<>();
        map.put("status",Orders.COMPLETED);
        map.put("minTime",minTime);
        map.put("maxTime",maxTime);

        //2. 查询商品名称及销量   select od.name name,sum(od.number) number from order_detail od  left join orders o on od.order_id = o.id
        //                                          where o.status = 5 and o.order_time >='2023-08-01 00:00:00'and order_time <= '2023-08-01 23:59:59'
        //                                          group by od.name order by sum(od.number) desc;
        List<GoodsSalesDTO> dto = ordersMapper.top10(map);
        //商品名称和销量列表集合
        List<String> nameList = new ArrayList<>();
        List<Integer> numberList = new ArrayList<>();
        for (GoodsSalesDTO salesDTO : dto) {
            nameList.add(salesDTO.getName());
            numberList.add(salesDTO.getNumber());
        }

        return SalesTop10ReportVO.builder()
                .nameList(StringUtils.join(nameList,","))
                .numberList(StringUtils.join(numberList,","))
                .build();
    }

    /**
     * 导出Excel报表接口
     * @param response
     */
    @Override
    public void export(HttpServletResponse response) throws IOException {
        //1. 获取近30天的运营数据报表
        //设置时间
        LocalDate end = LocalDate.now();
        LocalDate begin = end.minusDays(29);
        LocalDateTime beginTime = begin.atTime(LocalTime.MIN);
        LocalDateTime endTime = end.atTime(LocalTime.MAX);

        //2. 打印表格
        //创建Excel表格模板相对路径
        InputStream template = this.getClass().getClassLoader().getResourceAsStream("template.xlsx");
        //创建模板工作簿
        XSSFWorkbook xssfWorkbook = new XSSFWorkbook(template);
        //创建工作表
        XSSFSheet sheet = xssfWorkbook.getSheetAt(0);
        //设置时间
        sheet.getRow(1).getCell(1).setCellValue("时间: "+begin + "至" + end);
        //设置概览数据
        BusinessDataVO vo = workspaceService.getBusinessData(beginTime,endTime);
            //获取营业额
        sheet.getRow(3).getCell(2).setCellValue(vo.getTurnover());
            //获取订单完成率
        sheet.getRow(3).getCell(4).setCellValue(vo.getOrderCompletionRate());
            //获取新增用户数
        sheet.getRow(3).getCell(6).setCellValue(vo.getNewUsers());
            //获取有效订单
        sheet.getRow(4).getCell(2).setCellValue(vo.getValidOrderCount());
            //获取平均客单价
        sheet.getRow(4).getCell(4).setCellValue(vo.getUnitPrice());
        //设置明细数据
        //循环获取每日数据
        for (int i = 7; !begin.isAfter(end);begin = begin.plusDays(1),i++) {
            LocalDateTime minTime = begin.atTime(LocalTime.MIN);
            LocalDateTime maxTime = begin.atTime(LocalTime.MAX);
            //获取每日营业额
            BusinessDataVO dateVo = workspaceService.getBusinessData(minTime,maxTime);

            XSSFRow row = sheet.getRow(i);
            //日期
            row.getCell(1).setCellValue(begin.toString());
            //营业额
            row.getCell(2).setCellValue(dateVo.getTurnover());
            //有效订单
            row.getCell(3).setCellValue(dateVo.getValidOrderCount());
            //订单完成率
            row.getCell(4).setCellValue(dateVo.getOrderCompletionRate());
            //平均客单价
            row.getCell(5).setCellValue(dateVo.getUnitPrice());
            //新增用户数
            row.getCell(6).setCellValue(dateVo.getNewUsers());
        }
        xssfWorkbook.write(response.getOutputStream());
    }
}
